package com.imohoo.jni;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

/**
 * Created by zhaobo on 2016/5/10.
 */
public class Main {
    /** 加密 */
    public static final int ENCRYPT = 0;
    /** 解密 */
    public static final int DECRYPT = 1;

    /**
     * @param context 上下文
     * @param mode    1debug签名,2zoubo 3移动
     */
    public static void init(Object context, int mode) {
    }
//    System.out.println(decode("1raa70xiea6r1qm0", "83h8ew1kx0gcsn4x", aa));
//    System.out.println(decode("r4m75rga5vvqyop5", "05m90yncp5dvtj5d", aa));

    /**
     * aes 加密,base64编码
     *
     * @param data 字节数据
     * @param mode 0加密,1解密
     * @param mode 1密码1,2密码2
     */
    public static byte[] abc(byte[] data, int mode, int mode2) {
        int MODE = Cipher.DECRYPT_MODE;
        String key = "1raa70xiea6r1qm0";
        String iv = "83h8ew1kx0gcsn4x";
        if (mode == ENCRYPT) {
            MODE = Cipher.ENCRYPT_MODE;
        }
        if (mode2 == 2) {
            key = "r4m75rga5vvqyop5";
            iv = "05m90yncp5dvtj5d";
        }
        return docrypt(data, key.getBytes(), iv.getBytes(), MODE);
    }

    private static byte[] docrypt(byte[] content, byte[] keyBytes, byte[] ivBytes, int mode) {
        try {
            // 让java支持 AES/CBC/PKCS7Padding
            Security.addProvider(new BouncyCastleProvider());

            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); // keyBytes32个字节，256位，
            // 与C语言中的key一致
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");// 创建密码器

            cipher.init(mode, key, new IvParameterSpec(ivBytes));// 初始化

            return cipher.doFinal(content); // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
